package com.summer.core.schedule;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdScheduler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.summer.core.annotations.Logger;
import com.summer.core.schedule.job.AutoRemindLunchJob;

/**
 * 自动任务加载类
 */
@Component
public class InitJobs implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    StdScheduler scheduler;

    @Logger
    static Log log;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
        	//自动任务测试
        	autoRemindLunch();
			log.info("午饭就餐提醒！");

        }
    }

    /**
   	 * 提醒按时吃午饭~
   	 */
   	private void autoRemindLunch(){
   		CronTrigger trigger;
   		try {
   			trigger = (CronTrigger) scheduler.getTrigger(TriggerKey
   					.triggerKey("autoRemindLunchTrigger", "autoRemindLunch"));
   			if (trigger != null) {
   				trigger.getTriggerBuilder().withSchedule(CronScheduleBuilder.cronSchedule("0 55 11 * * ? *"));
   				scheduler.resumeTrigger(trigger.getKey());
   			} else {
   				// 生成新的job和trigger
   				JobDetail jobDetail = JobBuilder
   						.newJob(AutoRemindLunchJob.class)
   						.withIdentity("autoRemindLunchJob","autoRemindLunch")
   						.build();
   				trigger = TriggerBuilder
   						.newTrigger()
   						.withIdentity("autoRemindLunchTrigger", "autoRemindLunch")
   						.forJob(jobDetail)
   						.withSchedule(
   								CronScheduleBuilder.cronSchedule("0 55 11 * * ? *"))
   						.build();
   				
   				scheduler.scheduleJob(jobDetail, trigger);
   			}

   		} catch (SchedulerException e) {
   			e.printStackTrace();
   		}
   	}
    
   
}
